import { useConfigInfoStore } from "@/stores/ConfigInfo";
import { useUserInfoStore, type Token } from "@/stores/UserInfo";
import axios from "axios";
import { ElLoading, ElMessage } from "element-plus";
import jwt_decode from "jwt-decode";

// 配置授权参数
const config = {
	idsServer: window.baseUrl,
	response_type: "code",
	client_id: window.identityClient_id,
	redirect_uri: `${window.location.origin}/callback`,
	scope: "openid profile offline_access ceph_nex_scope1 user_scope1",
};

// 创建axios实例
const request = axios.create({
	baseURL: window.baseUrl,
	timeout: 20000,
});

// 请求ids文档,获取对应接口信息
const requestDoc = () => {
	return new Promise((resolve, reject) => {
		request({
			method: "get",
			url: `${config.idsServer}/.well-known/openid-configuration`,
		}).then((doc) => {
			resolve(doc.data);
		});
	});
};

// 参数格式化
const paramsFormat = (params: any) => {
	return Object.keys(params)
		.map((key) => `${key}=${params[key]}`)
		.join("&");
};

// 登录
export const login = async () => {
	let store = useConfigInfoStore();
	if (!store.identityServerDoc) {
		ElLoading.service({
			lock: true,
			text: "资源加载中...",
		});
		store.identityServerDoc = await requestDoc();
	}
	// 跳转到登录授权页面
	window.location.href = `${
		store.identityServerDoc.authorization_endpoint
	}?${paramsFormat(config)}`;
};

// 获取token
export const getToken = (code: string) => {
	return new Promise<Token>(async (resolve, reject) => {
		let store = useConfigInfoStore();
		if (!store.identityServerDoc) {
			ElLoading.service({
				lock: true,
				text: "资源加载中...",
			});
			store.identityServerDoc = await requestDoc();
		}
		let data = {
			grant_type: "authorization_code",
			code,
			client_id: config.client_id,
			redirect_uri: config.redirect_uri,
		};
		request({
			url: `${store.identityServerDoc.token_endpoint}`,
			method: "post",
			headers: {
				Accept: "*/*",
				"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
			},
			data: paramsFormat(data),
		}).then((res) => {
			resolve(res.data);
		});
	});
};

// refresh
export const refreshToken = (refresh_token: string) => {
	return new Promise<Token>(async (resolve, reject) => {
		let store = useConfigInfoStore();
		if (!store.identityServerDoc) {
			ElLoading.service({
				lock: true,
				text: "资源加载中...",
			});
			store.identityServerDoc = await requestDoc();
		}
		let data = {
			client_id: config.client_id,
			grant_type: "refresh_token",
			refresh_token,
		};
		request({
			url: store.identityServerDoc.token_endpoint,
			method: "post",
			headers: {
				Accept: "*/*",
				"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
			},
			data: paramsFormat(data),
		})
			.then((res) => {
				resolve(res.data);
			})
			.catch(async () => {
				await login();
			});
	});
};

// 注销
export const logout = async (id_token: string) => {
	let store = useConfigInfoStore();
	if (!store.identityServerDoc) {
		ElLoading.service({
			lock: true,
			text: "资源加载中...",
		});
		store.identityServerDoc = await requestDoc();
	}
	useUserInfoStore().$reset();
	window.location.href = `${store.identityServerDoc.end_session_endpoint}?id_token_hint=${id_token}`;
};
// token解析
export const tokenParse = (token: string) => {
	return jwt_decode(token);
};
